package com.wythe.mall.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wythe.mall.R;
import com.wythe.mall.adapter.GoodsBuyListAdapter;
import com.wythe.mall.base.BaseActivity;
import com.wythe.mall.intf.OnRequestDataListener;
import com.wythe.mall.model.AddressBean;
import com.wythe.mall.model.CarBean;
import com.wythe.mall.model.StoreBean;
import com.wythe.mall.utils.ApiOkHttp;
import com.wythe.mall.utils.GotoActivity;
import com.wythe.mall.utils.SharePreferenceUtils;
import com.wythe.mall.utils.ToastUtil;
import com.wythe.mall.utils.UserManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import top.yokey.base.bean.GoodsBuyBean;
import top.yokey.base.bean.StoreBuyBean;
import top.yokey.base.util.TextUtil;


public class BuyActivity extends BaseActivity implements View.OnClickListener {

    private Toolbar mainToolbar;
    private RelativeLayout addressRelativeLayout;
    private AppCompatTextView addressNameTextView;
    private AppCompatTextView addressMobileTextView;
    private AppCompatTextView addressAreaTextView;
    private AppCompatTextView payOnlineTextView;
    private AppCompatTextView invoiceNoTextView;
    private AppCompatTextView invoiceYesTextView;
    private RecyclerView mainRecyclerView;
    private LinearLayoutCompat redPacketLinearLayout;
    private AppCompatTextView redPacketTextView;
    private AppCompatTextView moneyTextView;
    private AppCompatTextView balanceTextView;
    private LinearLayout invoiceRelativeLayout, mTopPhone;


    private long exitTimeLong;
    private String jsonString;
    private GoodsBuyBean goodsBuyBean;
    private GoodsBuyListAdapter mainAdapter;
    private ArrayList<CarBean> mainArrayList;
    private List<AddressBean> mAddressLists;
    private AppCompatTextView daZheTextView;
    private AppCompatTextView robBuyTextView;
    private AppCompatTextView deliveryMethodTextView;
    private ImageView mIvInto;
    private EditText mEditPhone;
    private int totalCount;
    private double totalMoney;
    private StoreBean storeBean;
    private AddressBean addressBean;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_buy);
        Bundle bundle = getIntent().getExtras();
        mainArrayList = (ArrayList<CarBean>) bundle.getSerializable("list");
        totalCount = bundle.getInt("count");
        totalMoney = bundle.getDouble("money");
        if (mAddressLists == null) {
            mAddressLists = new ArrayList<>();
        }
        mAddressLists.clear();
        initView();
        initData();
        initEven();
    }

    public void initView() {
        storeBean = (StoreBean) SharePreferenceUtils.readObject(this, "store");
        findViewById(R.id.title_left_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ((TextView) findViewById(R.id.titleText)).setText("确认订单");
        daZheTextView = (AppCompatTextView) findViewById(R.id.daZheTextView);
        mIvInto = (ImageView) findViewById(R.id.iv_into);
        mEditPhone = (EditText) findViewById(R.id.et_phone);
        mTopPhone = (LinearLayout) findViewById(R.id.ll_top_phone);
        robBuyTextView = (AppCompatTextView) findViewById(R.id.robBuyTextView);
        addressRelativeLayout = (RelativeLayout) findViewById(R.id.addressRelativeLayout);
        addressRelativeLayout.setEnabled(false);
        addressNameTextView = (AppCompatTextView) findViewById(R.id.addressNameTextView);
        addressMobileTextView = (AppCompatTextView) findViewById(R.id.addressMobileTextView);
        addressAreaTextView = (AppCompatTextView) findViewById(R.id.addressAreaTextView);
        deliveryMethodTextView = (AppCompatTextView) findViewById(R.id.deliveryMethodTextView);
        if (storeBean != null) {
            addressNameTextView.setText(storeBean.getTitle());
            addressMobileTextView.setText(storeBean.getServicePhone());
            addressAreaTextView.setText(storeBean.getProvince() + storeBean.getCity() + storeBean.getDistrice() + storeBean.getAddress());
        }
        payOnlineTextView = (AppCompatTextView) findViewById(R.id.payOnlineTextView);
        payOnlineTextView.setText("￥" + totalMoney);
        invoiceNoTextView = (AppCompatTextView) findViewById(R.id.invoiceNoTextView);
        invoiceYesTextView = (AppCompatTextView) findViewById(R.id.invoiceYesTextView);
        mainRecyclerView = (RecyclerView) findViewById(R.id.mainRecyclerView);
        redPacketLinearLayout = (LinearLayoutCompat) findViewById(R.id.redPacketLinearLayout);
        redPacketTextView = (AppCompatTextView) findViewById(R.id.redPacketTextView);
        moneyTextView = (AppCompatTextView) findViewById(R.id.moneyTextView);
        moneyTextView.setText("合计： 共计" + totalCount + "件  ￥" + totalMoney);
        balanceTextView = (AppCompatTextView) findViewById(R.id.balanceTextView);
        invoiceRelativeLayout = (LinearLayout) findViewById(R.id.invoiceRelativeLayout);
        balanceTextView.setOnClickListener(this);

    }

    public void initData() {
        mainAdapter = new GoodsBuyListAdapter(this, mainArrayList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mainRecyclerView.setLayoutManager(linearLayoutManager);//设置布局管理器
        mainRecyclerView.setAdapter(mainAdapter);
    }

    public void initEven() {
        addressRelativeLayout.setOnClickListener(this);
        daZheTextView.setOnClickListener(this);
        robBuyTextView.setOnClickListener(this);
    }

    public void addOrder() {
        com.alibaba.fastjson.JSONObject param = new com.alibaba.fastjson.JSONObject();
        String phone = mEditPhone.getText().toString().trim();
        int addressId, mchSysUserId;
        int type;
        if ("门店自提".equals(deliveryMethodTextView.getText())) {
            if (TextUtils.isEmpty(phone)) {
                ToastUtil.show(this, "请先填写收货电话");
                return;
            }

            if (storeBean == null) {
                ToastUtil.show(this,"请先选择购物门店");
                return;
            }

            addressId = storeBean.getId();
            mchSysUserId = storeBean.getId();
            type = 1;
        } else {
            if (addressBean != null) {
                addressId = addressBean.getId();
                mchSysUserId = storeBean.getId();
            } else {
                ToastUtil.show(this, "请先填写收货地址");
                return;
            }

            type = 2;
        }
        param.put("addressId", addressId);
        param.put("itemList", mainArrayList);
        param.put("mchSysUserId", mchSysUserId);
        param.put("type", type);
        param.put("pickUpCall", phone);
        ApiOkHttp.addShopOrder(this, param, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                try {
                    String msg = data.getString("msg");
                    int code1 = data.getInt("code");
                    if (code1 == 200) {
                        JSONObject jsonObject = data.getJSONObject("data");
                        String orderNo = jsonObject.getString("orderNo");
                        double payAmount = jsonObject.getDouble("payAmount");
                        Bundle bundle = new Bundle();
                        bundle.putString("orderNo", orderNo);
                        bundle.putDouble("payAmount", payAmount);
                        GotoActivity.gotoActiviy(BuyActivity.this, PayOrderActivity.class, bundle);
                    } else {
                        ToastUtil.show(BuyActivity.this, msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.daZheTextView:
                daZheTextView.setTextColor(this.getResources().getColor(R.color.white));
                daZheTextView.setBackgroundResource(R.drawable.border_toolbar_left_press);
                robBuyTextView.setTextColor(this.getResources().getColor(R.color.greyAdd));
                robBuyTextView.setBackgroundResource(R.drawable.border_toolbar_right);
                addressRelativeLayout.setEnabled(false);
                deliveryMethodTextView.setText("门店自提");
                invoiceRelativeLayout.setVisibility(View.GONE);
                mIvInto.setVisibility(View.INVISIBLE);
                mTopPhone.setVisibility(View.VISIBLE);
                if (storeBean != null) {
                    addressNameTextView.setText(storeBean.getTitle());
                    addressMobileTextView.setText(storeBean.getServicePhone());
                    addressNameTextView.setText(storeBean.getTitle());
                    addressAreaTextView.setText(storeBean.getProvince() + storeBean.getCity() + storeBean.getDistrice() + storeBean.getAddress());
                }
                break;
            case R.id.robBuyTextView:
                daZheTextView.setTextColor(this.getResources().getColor(R.color.greyAdd));
                daZheTextView.setBackgroundResource(R.drawable.border_toolbar_left);
                robBuyTextView.setTextColor(this.getResources().getColor(R.color.white));
                robBuyTextView.setBackgroundResource(R.drawable.border_toolbar_right_press);
                addressRelativeLayout.setEnabled(true);
                deliveryMethodTextView.setText("商家配送");
                invoiceRelativeLayout.setVisibility(View.VISIBLE);
                mTopPhone.setVisibility(View.GONE);
                mIvInto.setVisibility(View.VISIBLE);
                getAddress();
                break;
            case R.id.addressRelativeLayout:
                Intent intent = new Intent(this, AddressActivity.class);
                startActivityForResult(intent, 100);
                break;
            case R.id.balanceTextView:
                addOrder();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 100) {
                Bundle bundle = data.getExtras();
                addressBean = (AddressBean) bundle.get("address");
                addressNameTextView.setText(addressBean.getName());
                addressMobileTextView.setText(addressBean.getMobile());
                addressAreaTextView.setText(addressBean.getProvince() + " " + addressBean.getCity() + " " + addressBean.getDistrice() + " " + addressBean.getAddress());
            }
        }
    }

    private void getAddress() {
        if (!UserManager.getInstance().isLogin()) {
            GotoActivity.gotoActiviy(this.getActivity(), LoginActivity.class);
            SharePreferenceUtils.removeString(this.getActivity(), "KEY_TOKEN");
            return;
        }
        JSONObject param = new JSONObject();
        ApiOkHttp.getAddressList(this, param, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                try {
                    mAddressLists.clear();
                    JSONArray data1 = data.getJSONArray("data");
                    for (int i = 0; i < data1.length(); i++) {
                        AddressBean bean = new Gson().fromJson(data1.getJSONObject(i).toString(), AddressBean.class);
                        mAddressLists.add(bean);
                    }

                    if (mAddressLists.size() > 0) {
                        addressBean = mAddressLists.get(0);
                        addressNameTextView.setText(addressBean.getName());
                        addressMobileTextView.setText(addressBean.getMobile());
                        addressAreaTextView.setText(addressBean.getProvince() + " " + addressBean.getCity() + " " + addressBean.getDistrice() + " " + addressBean.getAddress());
                    } else {
                        addressNameTextView.setText("新建收货地址");
                        addressMobileTextView.setText("");
                        addressAreaTextView.setText("");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });
    }
}
